import {recordList} from '@/utils/config.js'
import dayjs from 'dayjs'

import relativeTime from 'dayjs/plugin/relativeTime';
import isToday from 'dayjs/plugin/isToday';
import isYesterday from 'dayjs/plugin/isYesterday';

// 加载所需的dayjs插件
dayjs.extend(relativeTime);
dayjs.extend(isToday);
dayjs.extend(isYesterday);

export function formatTimeComparison(inputTime) {
  const now = dayjs();
  const input = dayjs(inputTime);
  
  // 计算时间差（分钟）
  const diffInMinutes = now.diff(input, 'minute');
  const absoluteDiff = Math.abs(diffInMinutes);
  
  // 获取时分部分（确保显示）
  const timePart = input.format('HH:mm');
  
  // 格式化时间差部分
  let diffText = '';
  if (absoluteDiff === 0) {
	diffText = '刚刚';
  } else if (absoluteDiff < 60) {
	diffText = `${absoluteDiff}分`;
  } else {
	const hours = Math.floor(absoluteDiff / 60);
	const minutes = absoluteDiff % 60;
	diffText = minutes > 0 ? `${hours}时${minutes}分` : `${hours}小时`;
  }
  
  // 确定时间方向（前/后）
  const direction = diffInMinutes >= 0 ? '前' : '后';
  
  // 根据日期返回不同格式
  if (input.isToday()) {
	return `今天 ${timePart} (${diffText}${direction})`;
  } else if (input.isYesterday()) {
	return `昨天 ${timePart} ${diffText}${direction}`;
  } else {
	// 更早日期显示完整日期+时间
	return input.format('YYYY-MM-DD HH:mm');
  }
}

const HISTORY = 'historyStore'


 /**
 * 分页工具函数（增强版）
 * @param {Array} totalData - 总数据数组
 * @param {number} currentPage - 当前页码（从 1 开始）
 * @param {number} pageSize - 每页显示的数据条数
 * @returns {Object} - 包含分页信息的对象
 */
export function paginateWithInfo(totalData, currentPage, pageSize=20) {
  // 校验参数
  if (!Array.isArray(totalData)) {
    throw new Error('totalData 必须是一个数组');
  }
  if (typeof currentPage !== 'number' || currentPage < 1) {
    throw new Error('currentPage 必须是一个大于等于 1 的数字');
  }
  if (typeof pageSize !== 'number' || pageSize <= 0) {
    throw new Error('pageSize 必须是一个大于 0 的数字');
  }

  // 计算总页数
  const totalPages = Math.ceil(totalData.length / pageSize);

  // 计算当前页的数据
  const startIndex = (currentPage - 1) * pageSize;
  const endIndex = currentPage * pageSize;
  const pageData = totalData.slice(startIndex, endIndex);

  // // 返回分页信息
  // return {
  //   currentPage,
  //   pageSize,
  //   totalPages,
  //   totalItems: totalData.length,
  //   pageData, // 当前页的数据
  // };
  return pageData
}

export const setHistoryList =(key,res)=>{
	
	
	let keyName = `${key}List`
	let historyList = uni.getStorageSync(keyName) || []
	if(historyList.length <= 0){
		historyList.unshift(res)
	}else{
		let historyId = res.historyId
		
		if(historyId){
			let index = historyList.findIndex(item=>item.historyId === historyId)
			historyList.splice(index,1,{
				...historyList[index],
				...res
			})
		}else{
			res.historyId = dayjs().valueOf()
			historyList.unshift(res)
		}
	}
	uni.setStorageSync(keyName,historyList)
}

export const getHistoryList =(key)=>{
	let keyName = `${key}List`
	return uni.getStorageSync(keyName) || []
}


export const getDataByKey = (key) =>{
	return recordList.find(item=>item.key == key)
}

export const getHistoryData = ()=>{
	console.log(uni.getStorageSync('historyStore'),'units');
	let historyData = uni.getStorageSync(HISTORY)
	if(!historyData){
		return []
	}
	
	return historyData.map(item=>{
		let {key} = item
		switch (key){
			case 'Breastfeeding':
				item.historyValue = item.actualMilkAmount
				break;
			case 'MixedFeeding':
				item.historyValue = item.actualMilkAmount
				break;
			case 'FormulaMilk':
				item.historyValue = `${item.actualMilkAmount} 毫升`
				break;
			case 'NutritionalSupplements':
				item.historyValue = `
					${item.equipmentName}
					${item.equipmentValue}
				`
				break;
			case 'WaterIntake':
				item.historyValue = `${item.actualMilkAmount} 毫升`
				break;
			case 'Pumping':
				item.historyValue = item.actualMilkAmount
				break;
			case 'DiaperChange':
				item.historyValue = item.actualMilkAmount
				break;
			case 'Pooping':
				item.historyValue = `
				${item.traitName} 
				${item.colorName} 
				${item.stoolOutputName}`
				break;
			case 'Urination':
				item.historyValue = `
				${item.traitName}
				${item.colorName} 
				${item.stoolOutputName}`
				break;
			case 'Sleep':
				item.historyValue = item.actualMilkAmount
				break;
			case 'SolidFood':
				item.historyValue = `
					${item.equipmentName}
					${item.equipmentValue}
				`
				break;
			case 'Bathing':
				item.historyValue = item.actualMilkAmount
				break;
			case 'Height':
				item.historyValue = `${item.actualMilkAmount} 厘米`
				break;
			case 'Weight':
				item.historyValue = `${item.actualMilkAmount} 千克  (${item.jin}斤)`
				break;
			case 'HeadCircumference':
				item.historyValue = `${item.actualMilkAmount} 厘米`
				break;
			case 'BodyTemperature':
				item.historyValue = `${item.actualMilkAmount} ℃`
				break;
			case 'Discomfort':
				item.historyValue = item.actualMilkAmount
				break;
			case 'Medication':
				item.historyValue = `
					${item.equipmentName}
					${item.equipmentValue}
				`
				break;
			case 'Vaccination':
				item.historyValue = item.name
				break;
			case 'Others':
				item.historyValue = item.actualMilkAmount
				break;
			default:
				break;
		}
		return item
	})
	
}


export const getHistoryDataById=(id)=>{
	let storeData = uni.getStorageSync(HISTORY)
	console.log(storeData,'新历史数据');
	return storeData.find(item=>item.id == id)
}


// 添加历史数据
export const setHistoryStore = (data) =>{
	let storeData = uni.getStorageSync(HISTORY)
	let day = dayjs().format('YYYY-MM-DD')
	let {key} = data
	let recordName= getDataByKey(key).name
	let pushData = {
		...data,
		key,
		recordName,
		dayValue:day
	}
	if(!storeData){
		uni.setStorageSync(HISTORY,[pushData])
	}else{
		storeData.unshift(pushData)
		uni.setStorageSync(HISTORY,storeData)
	}
	
	let newStoreData = uni.getStorageSync(HISTORY)
	
	console.log(newStoreData,HISTORY,'新的历史数据');
}

// 更新历史数据
export const updateHistoryStore = (id,res) =>{
	let historyStore = uni.getStorageSync(HISTORY)
	let index = historyStore.findIndex(item=>item.id == id)
	historyStore.splice(index,1,{
		...historyStore[index],
		...res
	})
	uni.setStorageSync(HISTORY,historyStore)
	console.log(uni.getStorageSync(HISTORY),'新历史数据');
}

// 删除历史数据
export const removeHistoryStore = (id)=>{
	let historyStore = uni.getStorageSync(HISTORY)
	let index = historyStore.findIndex(item=>item.id == id)
	historyStore.splice(index,1)
	uni.setStorageSync(HISTORY,historyStore)
}



export const removeStore = (type,id) =>{
	const currentStore = uni.getStorageSync(type)
	let historyStore = uni.getStorageSync(HISTORY)
	const updateDay = historyStore.find(item=>item.id == id).dayValue
	console.log(currentStore);
	let currentDayData = currentStore[updateDay]
	let currentDataIndex = currentDayData.findIndex(item=>item.id == id)
	let flagData = currentDayData[currentDataIndex]
	currentDayData.splice(currentDataIndex,1)
	
	// currentStore[updateDay] = currentDayData
	console.log(currentStore,type);
	uni.setStorageSync(type,currentStore)
	removeHistoryStore(id)
}



export const updateStore = (type,id,res) =>{
	const currentStore = uni.getStorageSync(type)
	let historyStore = uni.getStorageSync(HISTORY)
	const updateDay = historyStore.find(item=>item.id == id).dayValue
	console.log(currentStore);
	let currentDayData = currentStore[updateDay]
	let currentDataIndex = currentDayData.findIndex(item=>item.id == id)
	let flagData = currentDayData[currentDataIndex]
	currentDayData.splice(currentDataIndex,1,{
		...flagData,
		...res
	})
	
	// currentStore[updateDay] = currentDayData
	console.log(currentStore,type);
	uni.setStorageSync(type,currentStore)
	
	updateHistoryStore(id,res)
}

export const setStore = (key,data) =>{
	data.id = dayjs().valueOf()
	let storeData = uni.getStorageSync(key)
	let day = dayjs().format('YYYY-MM-DD')
	if(!storeData){
		uni.setStorageSync(key,{
			[day]:[data]
		})
	}else{
		let currentDayHasData = storeData[day]
		// 如果当天有值
		if(currentDayHasData){
			storeData[day].unshift(data)
		}else{
			storeData[day]=[data]
		}
		uni.setStorageSync(key,storeData)
	}
	setHistoryStore({
		...data,
		key
	})
}





/**
 * 将对象序列化为 URL 参数字符串
 * @param {Object} obj - 要序列化的对象
 * @returns {string} - 序列化后的 URL 参数字符串
 */
export const  serializeToUrlParams=(obj)=> {
  if (!obj || typeof obj !== 'object') {
    throw new Error('参数必须是一个对象');
  }

  // 使用 Object.entries 遍历对象的键值对
  return Object.entries(obj)
    .map(([key, value]) => {
      // 如果值是数组，则将每个元素单独编码
      if (Array.isArray(value)) {
        return value.map(v => `${encodeURIComponent(key)}[]=${encodeURIComponent(v)}`).join('&');
      }
      // 如果值是普通类型（字符串、数字等），直接编码
      return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
    })
    .join('&');
}